

const char* serverIndex = "<form method='POST' action='/update' enctype='multipart/form-data'><input type='file' name='update'><input type='submit' value='Update'></form>";




void handleRoot() {
  
  char temp[40096];
  int sec = millis() / 1000;
  int min = sec / 60;
  int hr = min / 60;

  snprintf(temp, 40096,

           "<html>\
  <head>\
    <meta http-equiv='refresh' content='5'/>\
    <title>ESP32 Demo</title>\
    <style>\
      body { background-color: #cccccc; font-family: Arial, Helvetica, Sans-Serif; Color: #000088; }\
    </style>\
  </head>\
  <body>\
    <h1>Hello from ESP8266!</h1>\
    <p>Uptime: %02d:%02d:%02d</p>\
    <p></p>\
    <p>GET /fs/append/{path}</p>\
    <p>GET /fs/read/{path}</p>\
    <p>GET /fs/write/{path}</p>\
    <p>GET /fs/delete/{path}</p>\
    <p>GET /config/read/{key}</p>\
    <p>GET /config/write/{key}/{value}</p>\
    <p>GET /on/{pin}</p>\
    <p>GET /off/{pin}</p>\
    <p>GET /dht/</p>\
    <p>GET /dht/all</p>\
    <p>GET /dht/clean</p>\
    <p>GET /upgrade</p>\
  </body>\
</html>", 

           hr, min % 60, sec % 60
          );
  server.send(200, "text/html", temp);
  
} 


void setupServer(){
  
  server.on("/", handleRoot);
  
  server.on("/upgrade", HTTP_GET, []() {    
    _info("GET /upgrade");
    server.sendHeader("Connection", "close");
    server.send(200, "text/html", serverIndex);
  });
  
  server.on(UriBraces("/voltage/{}"), []() {
    _info("GET /voltage/{pin}");
    int pin = server.pathArg(0).toInt();
    String v = getVoltage(pin);
    server.send(200, "text/plain", v);
  });  
  
  server.on(UriBraces("/config/read/{}"), []() {
    _info("GET /config/read/{key}");

    String key = server.pathArg(0);
    loadConfiguration();
    String value = doc[key];
    
    server.send(200, "text/plain", value);
  });   // /config/read
  
  
  server.on(UriRegex("^\\/config\\/write\\/([a-zA-Z]+)\\/(.+)$"), []() {
    _info("GET /config/write/{key}/{value}");

    String key = server.pathArg(0);
    String value = server.pathArg(1);
    doc[key] = value;
    
    saveConfiguration();
    
    server.send(200, "text/plain", value);
  });   // /config/read
  
  server.on(UriRegex("^\\/fs\\/read\\/(.+)$"), []() {
    _info("GET /fs/read/{}");

    String filename = server.pathArg(0);
    
    Serial.println( filename );

    String data = readFile(filename.c_str());
    server.send(200, "text/plain", data);
    
  });  // fs/read
  
  
  server.on(UriRegex("^\\/fs\\/write\\/(.+)$"), []() {
    _info("GET /fs/write/{}");

    String filename = server.pathArg(0);
    String data = "data..";
    
    String ret = writeFile(filename.c_str(), data.c_str() );
    Serial.println( ret );
    
    server.send(200, "text/plain", ret);
  });  // /fs/write
  
  
  server.on(UriRegex("^\\/fs\\/append\\/(.+)$"), []() {
    _info("GET /fs/append/{}");

    String filename = server.pathArg(0);
    String data = "data..\n";
    
    String ret = appendFile(filename.c_str(), data.c_str() );
    Serial.println( ret );
    
    server.send(200, "text/plain", ret);
  });   // /fs/append
  
  
  server.on(UriRegex("^\\/fs\\/list\\/(.+)$"), []() {
    _info("GET /fs/list/{path}");

    String path = server.pathArg(0); 

    listDir(path.c_str());  
    
  });   // /fs/list
  
  server.on("/fs/list", []() {
    _info("GET /fs/list");

    String path = "/"; 

    listDir(path.c_str());  
    
  });   // /fs/list
  
  server.on(UriRegex("^\\/fs\\/delete\\/(.+)$"), []() {
    _info("GET /fs/delete/{}");

    String filename = server.pathArg(0); 
    
    String ret = deleteFile( filename.c_str() );
    Serial.println( ret );
    
    server.send(200, "text/plain", ret);
  });   // /fs/delete
  
  server.on("/fs/format", []() {
    _info("GET /fs/format");  
      
    if (!SPIFFS.begin()) {
      Serial.println ("SPIFFS mount failed"); 
    }
  
    SPIFFS.format();    
    
    server.send(200, "text/plain", "/fs/format done.");
  });   // /fs/delete
  
  
  
  server.on("/dht", dhtRead);  
  server.on("/dht/all",  dhtReadAll ); 
  server.on("/dht/clean",  []() {
    _info("GET /dht/clean");

    deleteFile(dhtFilename);
    server.send(200, "text/plain", "dht data cleaned!");
  });  
  
  server.on(UriRegex("^\\/dht\\/server\\/(.+)$"), []() {
    _info("GET /dht/server/{}");

    String url = server.pathArg(0);
    
    Serial.println( url );
    doc["dhtServer"] = url;
    saveConfiguration();
    
    server.send(200, "text/plain", "dht server is set to: " + url);
  });  

  server.onNotFound([]() {
    server.send(404, "text/plain", "404 Not Found!");
  });

  server.on(UriBraces("/on/{}"), []() {
    isDht = false;
    
    String p = server.pathArg(0);
    int pin = p.toInt();
    pinMode(pin, OUTPUT);
    digitalWrite(pin, HIGH);
    server.send(200, "text/plain", "set PIN on: " + p );
  });

  server.on(UriBraces("/off/{}"), []() {
    
    isDht = false;
    
    String p = server.pathArg(0);
    
    int pin = p.toInt();
    pinMode(pin, OUTPUT);
    digitalWrite(pin, LOW);
    
    server.send(200, "text/plain", "set PIN off: " + p );
  });

  

  server.on(UriBraces("/analogRead/{}"), []() {
    
    _info("GET /analogRead/{pin}");
    
    String p = server.pathArg(0);
    
    int pin = p.toInt();
    uint16_t v = analogRead(pin); 
    
    server.send(200, "text/plain", String(v) );
    
  });

  

  server.on("/update", HTTP_POST, []() {
      server.sendHeader("Connection", "close");
      server.send(200, "text/plain", (Update.hasError()) ? "FAIL" : "OK");
      ESP.restart();
    }, []() {
      HTTPUpload& upload = server.upload();
      if (upload.status == UPLOAD_FILE_START) {
        Serial.setDebugOutput(true);
        WiFiUDP::stopAll();
        Serial.printf("Update: %s\n", upload.filename.c_str());
        uint32_t maxSketchSpace = (ESP.getFreeSketchSpace() - 0x1000) & 0xFFFFF000;
        if (!Update.begin(maxSketchSpace)) { //start with max available size
          Update.printError(Serial);
        }
      } else if (upload.status == UPLOAD_FILE_WRITE) {
        if (Update.write(upload.buf, upload.currentSize) != upload.currentSize) {
          Update.printError(Serial);
        }
      } else if (upload.status == UPLOAD_FILE_END) {
        if (Update.end(true)) { //true to set the size to the current progress
          Serial.printf("Update Success: %u\nRebooting...\n", upload.totalSize);
        } else {
          Update.printError(Serial);
        }
        Serial.setDebugOutput(false);
      }
      yield();
    }); // /update
   
} // setup server